package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.common.util.JsonResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
public class RegisterAndLoginController {

    @Reference
    private IUserInfoService userInfoService;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @ResponseBody
    @RequestMapping("/checkPhone")
    public Object checkPhone(String phone) {
        return !userInfoService.selectCountPhone(phone);
    }

    /**
     * 发送验证码
     * @param phone 手机号
     * @return 注册成功
     */
    @ResponseBody
    @RequestMapping("/sendVerifyCode")
    public Object sendVerifyCode(String phone) {
            userInfoService.sendVerifyCode(phone);
        return JsonResult.SUCCESS;
    }

    /**
     * 用户注册
     * @param phone 手机号
     * @param nickname 昵称
     * @param password 密码
     * @param rpassword 重复密码
     * @param verifyCode 验证码
     * @return 注册成功
     */
    @ResponseBody
    @RequestMapping("/userRegist")
    public Object regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
            userInfoService.regist(phone, nickname, password, rpassword, verifyCode);
        return JsonResult.SUCCESS;
    }

    /**
     * 用户登录验证
     * @param username 用户名
     * @param password 密码
     * @return  登录成功
     */
    @ResponseBody
    @RequestMapping("/userLogin")
    public Object checkLogin(String username, String password, HttpServletResponse response){
        //验证账户密码
        String token = userInfoService.login(username, password);
        /**
         * 发送cookie到浏览器中
         * cookie需要设置失效时间
         * cookie需要注意路劲区分
         */
        Cookie cookie = new Cookie("token",token);
        CookieUtil.addCookie(response,cookie);
        return JsonResult.SUCCESS;
    }


}